package cz.muni.fi.pa165.web;

import cz.muni.dto.TarrifDTO;
import cz.muni.service.TarrifServiceLocal;
import java.util.List;
import javax.ejb.EJB;
import net.sourceforge.stripes.action.*;
import net.sourceforge.stripes.controller.LifecycleStage;
import net.sourceforge.stripes.validation.Validate;
import net.sourceforge.stripes.validation.ValidateNestedProperties;
import sun.java2d.pipe.SpanShapeRenderer;
import net.sourceforge.stripes.validation.SimpleError;

@UrlBinding("/TarrifManager.{$event}")
public class ManagerTarrifActionBean implements ActionBean {
    
    @EJB(mappedName = "java:global/DeliveryCompany-web/TarrifService!cz.muni.service.TarrifServiceLocal")
    private TarrifServiceLocal tarrifService;

    @DefaultHandler
    public Resolution home() {
        return new ForwardResolution("");
    }

    
    @HandlesEvent("save")
    public Resolution save() {
        tarrifService.create(tarrif);
        return new RedirectResolution("/manager_tariffs.jsp");
    }
    
    @ValidateNestedProperties({
        @Validate(field="name", required=true, maxlength=75),
        @Validate(field="pricePerKG", required=true),
        @Validate(field="pricePerKM", required=true),
        @Validate(field="deliveryFee", required=true)
    })
    private TarrifDTO tarrif;

    public TarrifDTO getTarrif() {
        return tarrif;
    }

    public void setTarrif(TarrifDTO tarrif) {
        this.tarrif = tarrif;
    }

    public List<TarrifDTO> getTarrifs() {
        return tarrifService.findAll();
    }

    @DontValidate
    @Before(stages = LifecycleStage.BindingAndValidation, on = {"edit", "update"})
    public void loadTarrifFromDatabase() {
        String ids = context.getRequest().getParameter("tarrif.id");
        if (ids == null) return;
        tarrif = tarrifService.find(Long.parseLong(ids));
    }
 
    @DontValidate
    public Resolution edit() {
        return new ForwardResolution("/editTarrif.jsp");
    }
    
    @DontValidate
    public Resolution back() {
        return new ForwardResolution("/manager_tariffs.jsp");
    }
 
    @DontValidate
    public Resolution update() {
        tarrifService.update(tarrif);
        return new RedirectResolution("/manager_tariffs.jsp");
    }
    
    @DontValidate
    public Resolution delete() {
        try {
            tarrifService.delete(tarrif);
        } catch (Exception e) {
            return new RedirectResolution("/manager_error.jsp");
        }
        return new RedirectResolution("/manager_tariffs.jsp");
    }
    
    private ActionBeanContext context;
    
    @Override
    public void setContext(ActionBeanContext context) {
        this.context = context;
    }

    @Override
    public ActionBeanContext getContext() {
        return context;
    }
}
